package com.bu.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collection;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.bu.model.Problem;
import com.bu.model.Topic;
import com.bu.service.PMF;
import com.google.appengine.api.datastore.Text;

/**
 * @author xueqiang.mi
 * @since 2011-2-24
 */
@Path("/data")
@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class DataResource extends BaseResource {

	@SuppressWarnings("unchecked")
	@GET
	@Path("clean")
	@Produces("text/plain")
	public String clean() {
		PersistenceManager pm = PMF.get();
		try {
			// clean up problems
			Query q = pm.newQuery(Problem.class);
			Collection<Problem> c = (Collection<Problem>) q.execute();
			pm.deletePersistentAll(c);
			// clean up topics
			q = pm.newQuery(Topic.class);
			c = (Collection<Problem>) q.execute();
			pm.deletePersistentAll(c);
		} finally {
			pm.close();
		}
		return "OK";
	}

	@GET
	@Path("store/{index}")
	@Produces("text/plain")
	public String store(@PathParam("index") int index) throws IOException {
		URL url = new URL("http://latexproblem.appspot.com/data.txt");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoInput(true);
		conn.connect();
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line = reader.readLine();
		int i = 0;
		while (line != null) {
			if (!line.endsWith("\"") || !line.contains("\",\"")) {
				line += reader.readLine();
				continue;
			}
			String[] tmp = line.split("\",\"");
			if (tmp.length != 2) {
				System.err.println("Error on:" + line);
			}
			if (index == 0) {
				insert(tmp[1].substring(0, tmp[1].length() - 1), tmp[0].substring(1));
			} else {
				i++;
				if (i > index) {
					insert(tmp[1].substring(0, tmp[1].length() - 1), tmp[0].substring(1));
				}
			}
			line = reader.readLine();
		}
		return "OK";
	}

	private void insert(String topics, String problem) {
		Problem p = new Problem();
		p.setTopics(topics);
		p.setProblem(new Text(problem));
		p.setSolution(new Text(""));
		p.setSource("");
		p.setDifficulty(0.0f);
		p.setNote(new Text(""));
		problemService.add(p);
	}
}
